package com.zz.yt.lib.annex.picture.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.glide.GlideEngine;
import com.zz.yt.lib.annex.glide.ImageFileCropEngine;
import com.zz.yt.lib.annex.utils.LocalMediaUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 选择文件的工具类
 *
 * @author qf
 * @version 2020-04-05
 */
public final class AnnexPictureUtil implements OnResultCallbackListener<LocalMedia>,
        OnExternalPreviewEventListener {

    private Activity act;
    private Fragment fra;
    private boolean camera;
    private OnClickListener mClickListener = null;

    /**
     * 总共个数，默认9个
     */
    private int maxSelectNum = 9;

    /**
     * 是否单张图片选择，默认是false
     */
    private boolean isRadio;

    /*** 是否图片裁剪，默认是false*/
    private boolean isCropping;

    private AnnexPictureUtil() {

    }

    @NonNull
    public static AnnexPictureUtil Bundle() {
        return new AnnexPictureUtil();
    }

    /**
     * @param context：上下文对象
     */
    public AnnexPictureUtil setContent(Context context) {
        this.act = (Activity) context;
        return this;
    }

    /***
     * 注：AppCompatActivity或者FragmentActivity，不能是Activity
     * @param activity：上下文对象
     */
    public AnnexPictureUtil setContent(Activity activity) {
        this.act = activity;
        return this;
    }

    /**
     * @param fragment：上下文对象
     */
    public AnnexPictureUtil setContent(Fragment fragment) {
        this.fra = fragment;
        return this;
    }

    /**
     * @param maxSelectNum 可选择文件数量
     */
    public AnnexPictureUtil setMaxCount(int maxSelectNum) {
        return setMaxSelectNum(maxSelectNum);
    }


    /**
     * @param maxSelectNum 可选择文件数量
     */
    public AnnexPictureUtil setMaxSelectNum(int maxSelectNum) {
        this.maxSelectNum = maxSelectNum;
        return this;
    }

    /**
     * @param radio: 是否单选
     */
    public AnnexPictureUtil setRadio(boolean radio) {
        isRadio = radio;
        return this;
    }

    /**
     * @param cropping: 是否裁剪
     */
    public AnnexPictureUtil setCropping(boolean cropping) {
        isCropping = cropping;
        return this;
    }

    /**
     * @param camera：是否仅拍照
     */
    public AnnexPictureUtil setCamera(boolean camera) {
        this.camera = camera;
        return this;
    }

    /**
     * @param listener：选择回调
     */
    public AnnexPictureUtil forResult(OnClickListener listener) {
        this.mClickListener = listener;
        return this;
    }

    /**
     * 获取拍照权限
     */
    public void init() {
        PermissionUtils
                .permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(@NonNull UtilsTransActivity activity, @NonNull ShouldRequest shouldRequest) {
                        shouldRequest.again(true);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissionsGranted) {
                        LatteLogger.d("权限获取成功", permissionsGranted);
                        if (camera) {
                            openCamera();
                        } else {
                            openGallery();
                        }
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissionsDeniedForever, @NonNull List<String> permissionsDenied) {
                        LatteLogger.d("权限永久拒绝", permissionsDeniedForever);
                        LatteLogger.d("权限拒绝", permissionsDenied);
                    }
                })
                .theme(new PermissionUtils.ThemeCallback() {
                    @Override
                    public void onActivityCreate(@NonNull Activity activity) {
                        ScreenUtils.setFullScreen(activity);
                    }
                })
                .request();
    }

    /**
     * 单独拍照
     */
    private void openCamera() {
        if (ObjectUtils.isNotEmpty(fra)) {
            PictureSelector.create(fra)
                    .openCamera(SelectMimeType.ofImage())
                    .forResult(this);
            return;
        }
        if (ObjectUtils.isEmpty(act)) {
            act = Latte.getActivity();
        }
        final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (act.getFragmentManager() != null &&
                takePictureIntent.resolveActivity(act.getPackageManager()) != null) {
            PictureSelector.create(act)
                    .openCamera(SelectMimeType.ofImage())
                    .forResult(this);
        } else {
            //未获取到相机应用，使用系统相机
            openSystemGallery();
        }
    }

    /**
     * 获取图片
     */
    private void openGallery() {
        if (ObjectUtils.isNotEmpty(fra)) {
            PictureSelector.create(fra)
                    .openGallery(SelectMimeType.ofImage())
                    .setMaxSelectNum(maxSelectNum)
                    .setSelectionMode(isRadio ? SelectModeConfig.SINGLE : SelectModeConfig.MULTIPLE)
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setCropEngine(isCropFileEngine())
                    .forResult(this);
            return;
        }
        if (ObjectUtils.isEmpty(act)) {
            act = Latte.getActivity();
        }
        PictureSelector.create(act)
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(maxSelectNum)
                .setSelectionMode(isRadio ? SelectModeConfig.SINGLE : SelectModeConfig.MULTIPLE)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setCropEngine(isCropFileEngine())
                .forResult(this);
    }

    /**
     * 使用系统相册
     */
    private void openSystemGallery() {
        if (ObjectUtils.isNotEmpty(fra)) {
            PictureSelector.create(fra)
                    .openSystemGallery(SelectMimeType.ofImage())
                    .setSelectionMode(isRadio ? SelectModeConfig.SINGLE : SelectModeConfig.MULTIPLE)
                    .setCropEngine(isCropFileEngine())
                    .forSystemResult(this);
            return;
        }
        if (ObjectUtils.isEmpty(act)) {
            act = Latte.getActivity();
        }
        PictureSelector.create(act)
                .openSystemGallery(SelectMimeType.ofImage())
                .setSelectionMode(isRadio ? SelectModeConfig.SINGLE : SelectModeConfig.MULTIPLE)
                .setCropEngine(isCropFileEngine())
                .forSystemResult(this);
    }

    /**
     * 裁剪引擎
     */
    @Nullable
    private ImageFileCropEngine isCropFileEngine() {
        return isCropping ? new ImageFileCropEngine() : null;
    }

    @Override
    public void onResult(ArrayList<LocalMedia> result) {
        if (mClickListener != null) {
            final List<String> resultStr = LocalMediaUtils.upPath(result);
            mClickListener.onClick(resultStr, result);
        }
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onPreviewDelete(int position) {
        if (mClickListener != null) {
            mClickListener.onPreviewDelete(position);
        }
    }

    @Override
    public boolean onLongPressDownload(Context context, LocalMedia media) {
        return false;
    }

    /**
     * 选中的附件回调
     */
    public interface OnClickListener {

        /***
         * 选中的附件
         * @param path：选中的附件
         */
        void onClick(List<String> path, ArrayList<LocalMedia> media);

        /***
         * 删除图片
         * @param position:删除的下标
         */
        void onPreviewDelete(int position);
    }

}
